package com.itheima.dao.impl;

import com.itheima.dao.RoleDao;
import com.itheima.domain.Role;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class RoleDaoImpl implements RoleDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<Role> findAll() {
        List<Role> roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper<Role>(Role.class));
        return roleList;
    }

    @Override
    public void save(Role role) {
        jdbcTemplate.update("insert into sys_role values ( ? , ? , ? )",null,role.getRoleName(),role.getRoleDesc());
    }

    @Override
    public List<Role> findRolesByUid(Long id) {
        List<Role> roleList = jdbcTemplate.query("select * from sys_user_role ur , sys_role r where ur.roleId = r.id and userId = ? ", new BeanPropertyRowMapper<Role>(Role.class), id);
        return roleList;
    }

    @Override
    public void saveRoleAndUserRel(Long uid, Long[] roleIds) {
        for (Long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role values ( ? , ? )",uid,roleId);
        }

    }

    @Override
    public void del(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId = ? ",userId);
    }
}
